<!-- 完形填空 -->
<template>
  <el-row>
    <!-- 题目 -->
    <el-row id="row1">
      <el-col :span="24">
        <el-form-item :label="$t('paperQuestionLangList.question')">
          <richTextCom v-model="questionGroup" :group="questionGroup" :showAudioTool="false"/>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 小题个数 -->
    <el-row id="row1">
      <el-col :span="24">
        <el-form-item :label="$t('paperQuestionLangList.questionLowCount')">
          <el-select v-model="questionLowModel" @change="questionLowModelChange">
            <el-option v-for="item in questionLowCount" :key="item" :label="item" :value="item"/>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 选项个数 -->
    <el-row>
      <el-col :span="24">
        <el-form-item :label="$t('paperQuestionLangList.optionCount')">
          <optionChooseCom v-model="chooseOption" :option-array="optionArray" @clickCallback="optionClickCallback"/>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 选项内容 -->
    <el-row id="row7">
      <el-col :span="24">
        <el-row v-for="(item, index) in optionGroupArray" :key="index">
          <el-form-item :label="$t('paperQuestionLangList.questionLow') + (index + 1)">
            <div class="option-radio-list">
              <template v-for="optionItem in item.option">
                <div class="option-radio-item">
                  <el-radio v-model="item.answerKey" :label="optionItem.optionKey" border/>
                  <el-input v-model="optionItem.optionTxt" type="text"/>
                </div>
              </template>
            </div>
          </el-form-item>
          <el-form-item :label="$t('paperQuestionLangList.analysis')">
            <div class="option-radio-analysis">
              <el-input :row="2" v-model="item.analysisTxt" type="textarea"/>
            </div>
          </el-form-item>
        </el-row>
      </el-col>
    </el-row>
    <!-- 添加标签 -->
    <el-row id="row5">
      <el-col :span="24">
        <el-form-item :label="$t('paperQuestionLangList.addTags')">
          <paperTagsCom v-model="chooseTags" :qId="qId" :show-btn="false"/>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 操作按钮 -->
    <div class="form-footer">
      <el-row type="flex" justify="center">
        <el-button type="primary" @click="savePaperQuestion(1)">{{ $t('form.save') }}</el-button>
        <el-button v-if="!isEdit" type="primary" @click="savePaperQuestion(2)">{{ $t('paperQuestionLangList.goOnAddQuestion') }}</el-button>
      </el-row>
    </div>
  </el-row>
</template>

<script>
import richTextCom from './richText'
import optionChooseCom from './optionChoose'
import paperTagsCom from '../paperTags'
import { createdQuestion, getQuestionDetail, updateQuestion } from '@/api/question'
import { updatePaperQuestion } from '@/api/paper'
export default {
  name: 'Cloze',
  components: {
    richTextCom,
    optionChooseCom,
    paperTagsCom
  },
  props: {
    // 试卷id
    parentPaperId: String,
    newEditType: String,
    categoryProps: {
      type: String,
      default: 'cloze'
    }
  },
  data() {
    return {
      // 小题个数
      questionLowCount: new Array(20).fill(1).map((v, i) => i + 1),
      // 小题默认个数
      questionLowModel: 3,
      chooseOption: 4,
      // 选项个数
      optionArray: [2, 3, 4],
      // 题目文本信息
      questionGroup: {
        category: '',
        subjectTxt: '',
        subjectAudio: ''
      },
      // 选项内容文本信息数组
      optionGroupArray: [],
      // 字母数组
      letterArray: [],
      // 解析
      analysisGroup: {
        category: '',
        subjectTxt: '',
        subjectAudio: ''
      },
      // 正确答案
      answerRadio: '',
      // 选择的标签
      chooseTags: [],
      // 是否可提交标志
      submitFlag: false,
      qId: '',
      isEdit: false
    }
  },
  watch: {
    // 监听选项个数改变
    // 'chooseOption': function(val) {
    //   this.initOption()
    //   console.info(val)
    // },
    // 监听标签选择
    'chooseTags': function(val) {
      console.info(val)
    }
    // 监听小题个数
    // 'questionLowModel': function(val) {
    //   this.initOption()
    //   console.info(val)
    // }
  },
  created() {
    console.info(this.parentPaperId)
    this.initPage()
  },
  methods: {
    // 初始化页面
    initPage() {
      this.questionGroup.category = this.categoryProps
      this.analysisGroup.category = this.categoryProps
      this.initOption()
    },
    // 初始化选项内容
    initOption() {
      this.optionGroupArray = []
      for (let i = 0; i < this.questionLowModel; i++) {
        // 选项内容
        const optionArray = []
        const letterArray = []
        for (let j = 0; j < this.chooseOption; j++) {
          const letter = String.fromCharCode(j + 65)
          letterArray.push(letter)
          const obj = {
            optionTxt: '',
            optionAudio: '',
            optionKey: letter
          }
          optionArray.push(obj)
        }
        const obj = {
          subjectTxt: '',
          subjectAudio: '',
          analysisTxt: '',
          analysisAudio: '',
          option: optionArray,
          answerKey: letterArray[0]
        }
        this.optionGroupArray.push(obj)
      }
    },
    // 初始化数据
    initData() {
      this.chooseOption = 4
      this.questionLowModel = 3
      this.questionGroup = {
        category: 'cloze',
        subjectTxt: '',
        subjectAudio: ''
      }
      this.optionGroupArray = []
      this.initOption()
      this.letterArray = []
      this.analysisGroup = {
        category: 'cloze',
        subjectTxt: '',
        subjectAudio: ''
      }
      this.answerRadio = ''
      this.chooseTags = []
      this.submitFlag = false
      this.qId = ''
      this.isEdit = false
      this.$refs.tags.initPage()
    },
    // 编辑时加载数据
    initUpdateData(row) {
      const _this = this
      _this.isEdit = true
      const loading = _this.$loading({
        lock: true,
        text: '数据加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.6)'
      })
      getQuestionDetail(row.id).then(res => {
        loading.close()
        if (res) {
          res.questions.forEach(v => {
            v.option = v.options
          })
          _this.optionGroupArray = res.questions
          _this.questionGroup.subjectTxt = res.groupSubjectTxt
          _this.questionGroup.category = res.category
          _this.questionGroup.subjectAudio = res.groupSubjectAudio
          _this.analysisGroup.subjectTxt = res.questions[0].analysisTxt
          _this.chooseOption = res.questions[0].option.length
          _this.questionLowModel = res.questions.length
          _this.qId = row.id
        }
      }).catch(err => {
        loading.close()
        console.info(err)
      })
    },
    questionLowModelChange(val) {
      this.questionLowModel = val
      this.initOption()
    },
    optionClickCallback(val) {
      this.chooseOption = val
      this.initOption()
    },
    // 表单验证
    formValidator() {
      if (this.questionGroup.subjectTxt.trim() === '') {
        this.$message({
          message: '请填写题目信息',
          type: 'warning'
        })
        document.getElementById('row1').scrollIntoView()
        return
      }
      if (this.chooseTags.length === 0) {
        this.$message({
          message: '请选择至少一个标签',
          type: 'warning'
        })
        document.getElementById('row5').scrollIntoView()
        return
      }
      // 选项内容填写数组
      const optionContent = this.optionGroupArray
      let idx = ''
      for (let i = 0; i < optionContent.length; i++) {
        for (let j = 0; j < optionContent[i].option.length; j++) {
          if (optionContent[i].option[j].optionTxt.trim() === '') {
            idx = j
            break
          }
        }
      }
      if (idx !== '') {
        this.$message({
          message: '请填写全部小题选项内容',
          type: 'warning'
        })
        document.getElementById('row7').scrollIntoView()
        return
      }
      this.submitFlag = true
    },
    // 保存
    savePaperQuestion(type) {
      const _this = this
      _this.formValidator()
      // 执行保存
      if (_this.submitFlag) {
        // 提交数据
        const postData = {
          group: JSON.stringify(_this.questionGroup),
          labelIds: _this.chooseTags.join(','),
          category: _this.categoryProps,
          question: JSON.stringify(_this.optionGroupArray)
        }
        const loading = _this.$loading({
          lock: true,
          text: '数据保存中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.6)'
        })
        // 新增
        if (!_this.isEdit) {
          createdQuestion(postData).then(res => {
            if (res) {
              if (_this.newEditType == 'question') {
                loading.close()
                // 保存
                if (type == 1) {
                  _this.$emit('saveCallback')
                }
                // 继续录题
                else if (type == 2) {
                  _this.initData()
                }
              } else {
                const questionId = res.id
                const postData2 = {
                  questionIds: questionId
                }
                // 更新试卷下的试题
                updatePaperQuestion(_this.parentPaperId, postData2).then(res => {
                  _this.$message({
                    message: '保存成功',
                    type: 'success'
                  })
                  loading.close()
                  // 保存
                  if (type == 1) {
                    _this.$emit('saveCallback')
                  }
                  // 继续录题
                  else if (type == 2) {
                    _this.initData()
                  }
                }).catch(err => {
                  loading.close()
                  console.info(err)
                })
              }
            }
          }).catch(err => {
            loading.close()
            console.info(err)
          })
        }
        // 编辑
        else {
          if (_this.newEditType == 'question') {
            postData._method = 'PUT'
            updateQuestion(_this.qId, postData).then(res => {
              _this.$message({
                message: '保存成功',
                type: 'success'
              })
              loading.close()
              // 保存
              if (type == 1) {
                _this.$emit('saveCallback')
              }
              // 继续录题
              else if (type == 2) {
                _this.initData()
              }
            }).catch(err => {
              loading.close()
              console.info(err)
            })
          } else {
            postData._method = 'PUT'
            updateQuestion(_this.qId, postData).then(res => {
              if (res) {
                const questionId = res.id
                const postData2 = {
                  questionIds: questionId
                }
                // 更新试卷下的试题
                updatePaperQuestion(_this.parentPaperId, postData2).then(res => {
                  _this.$message({
                    message: '保存成功',
                    type: 'success'
                  })
                  loading.close()
                  // 保存
                  if (type == 1) {
                    _this.$emit('saveCallback')
                  }
                  // 继续录题
                  else if (type == 2) {
                    _this.initData()
                  }
                }).catch(err => {
                  loading.close()
                  console.info(err)
                })
              }
            })
          }
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .option-radio-list {
    display: flex;
    .option-radio-item {
      display: flex;
      /deep/ .el-input__inner {
        width: 160px;
        margin-right: 10px;
      }
      .el-radio {
        margin-right: 15px;
      }
    }
  }
  /deep/ .option-radio-analysis textarea {
    width: 720px;
  }
</style>
